/*
 * pixiv_down - CLI-based downloading tool for https://www.pixiv.net.
 * Copyright (C) 2025  Mio
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
module app.cmds.errors;

import std.stdio;

import mlib.directories;

import pd.configuration;
import pd.error_cache;

struct ErrorsConfig
{
    bool cleanCache;
}

int errorsHandle(string[] args, const ref Config config)
{
    ErrorsConfig ec;

    foreach(const ref arg; args[1..$]) {
        switch (arg) {
            case "--clean":
                ec.cleanCache = true;
                break;
            case "--help":
            case "-h":
                displayErrorsHelp();
                return 0;
            default:
                stderr.writefln("warning: unknown argument to 'errors' comment: %s", arg);
                break;
        }
    }

    runErrors(ec);

    return 0;
}

void displayErrorsHelp()
{
    stdout.writeln("pixiv_down errors - Print failed download IDs to the standard output\n" ~
		   "\nUsage:\tpixiv_down errors [--clean]\n" ~
		   "\nThis command will print all works that have failed to download from any previous\n" ~
		   "invocation of pixiv_down.  Works are removed from the cache if they are successfully\n" ~
		   "downloaded later on.  You can manually clean the entire cache by passing then\n" ~
		   "--clean option.\n" ~
		   "\nOptions:\n" ~
		   "    -h, --help\tDisplay this help message and exit\n" ~
		   "    --clean   \tClean the cache of errors");
}

private:

void runErrors(const ref ErrorsConfig config)
{
    import std.algorithm.iteration: each;
    import std.file: FileException;
    import std.path: buildPath;
    import mlib.trash: trash;

    const ProjectDirectories dirs = getProjectDirectories(null, "YumeNeru Software", "pixiv_down");

    if (config.cleanCache) {
        try {
            trash(buildPath(dirs.stateDir, "errors"));
        } catch (FileException) {
            // Don't error if it doesn't exist.
        }
        return;
    }

    ErrorCache cache = loadErrorCache();

    if (cache.artworks.length() > 0) {
        writeln("Artworks:");
        cache.artworks.each!writeln;
    }

    if (cache.novels.length() > 0) {
        writeln("Novels:");
        cache.novels.each!writeln;
    }
}

